<template>
    <form class="validate-form-container d-flex flex-column">
        <slot></slot>
        <div class="submit-area align-self-start" @click.prevent="clickSubmit">
            <slot name="submit"><button type="submit" class="btn btn-primary">提交</button></slot>
        </div>
    </form>
</template>

<script lang="ts">
import { defineComponent, onMounted, onUnmounted } from "vue";
import mitt, { Emitter } from "mitt";
export const emitter: Emitter = mitt();
type ValidateFunc = () => boolean;
export default defineComponent({
    emits: ["form-submit"],
    setup(props, { emit }) {
        let validateFuncArr: ValidateFunc[] = [];
        const clickSubmit = () => {
            const validateResult = validateFuncArr.map(func => func()).every(bool => bool);
            emit("form-submit", validateResult);
        };
        const callback = (func: ValidateFunc) => {
            validateFuncArr.push(func);
        };
        emitter.on("form-item-created", callback);
        onUnmounted(() => {
            emitter.off("form-item-created", callback);
            validateFuncArr = [];
        });
        return {
            clickSubmit,
        };
    },
});
</script>

<style scoped lang="scss"></style>
